package com.zhisheng.redis_hello.service.impl;

import com.zhisheng.redis_hello.entity.Student;
import com.zhisheng.redis_hello.service.StudentService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {

    // Redis中存储学生信息的哈希key前缀（避免key冲突）
    private static final String STUDENT_KEY_PREFIX = "student:";

    private final RedisTemplate<String, Object> redisTemplate;

    // 构造注入RedisTemplate
    public StudentServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void addStudent(Student student) {
        // 构建Redis哈希的完整key（前缀+学生ID）
        String key = STUDENT_KEY_PREFIX + student.getId();

        // 将学生信息封装为Map（哈希的field-value键值对）
        Map<String, Object> studentMap = new HashMap<>();
        studentMap.put("name", student.getName());
        studentMap.put("age", student.getAge());
        studentMap.put("className", student.getClassName());

        // 使用putAll方法存储哈希数据
        redisTemplate.opsForHash().putAll(key, studentMap);
    }

    @Override
    public Map<Object, Object> getStudentById(String id) {
        // 构建Redis哈希的完整key
        String key = STUDENT_KEY_PREFIX + id;

        // 使用entries方法获取哈希中所有field-value键值对
        return redisTemplate.opsForHash().entries(key);
    }
}